<template>
    <div v-if="reload">
        <el-form :inline="true" ref="form" :model="form" :rules="rules" class="search-form" label-width="100px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="计划编号：">
                        {{ form.shipPlanNo }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="船名：" prop="shipName">
                        <auto-search-ship @selectName="v=>form.shipName=v" @selectCode="v=>form.shipCode=v"
                                          :name="form.shipName"
                                          ship="shipCName"></auto-search-ship>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="航次：" prop="voyage">
                        <el-input v-model="form.voyage"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口：" prop="portCode">
                        <select-port v-model="form.portCode" :name="form.portCode"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="计划类型：" prop="planType">
                        <!--{{ form.planType | _filterShipPlanType }}-->
                        卸船
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业状态：" prop="planStatus">
                        {{ form.planStatus | _filterTallyPlanStatus }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="完成日期：">
                        {{ form.taskTime }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="数据来源：">
                        {{ form.planFrom }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="创建时间：">
                        {{ form.createDateTime }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="封航日期：">
                        {{ form.feeCloseTime }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="封航时间：">
                        {{ form.closeTime }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="封航人：">
                        {{ form.closeUser }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row type="flex" justify="center">
                <el-button @click="downExcel" style="margin-left: 10px;height: 33px;margin-right: 15px;">下载导入模板</el-button>
                <attachments v-model="titleMessage" :isSingle="isSingle" :isLimit="isLimit" :btnName="btnName" :isGoStop = "(form.portCode == null || form.portCode == '')" @upload="uploadsExcel"></attachments>
                <el-button type="primary" @click="handleSubmit" style="margin-left: 10px;height: 33px;">保 存</el-button>
            </el-row>
        </el-form>
        <div class="border-line-dashed mt-10 mb-10"></div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="80px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="箱号">
                        <el-input v-model="condition['search_LIKE_containerId']"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="箱型">
                        <autoSearchEntrust v-model="condition['search_LIKE_containerType']"
                                           :name="condition['search_LIKE_containerType']"></autoSearchEntrust>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="尺寸">
                        <autoSearchSize v-model="condition['search_EQ_containerSize']"></autoSearchSize>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="内外贸">
                        <el-select v-model="condition['search_EQ_tradeType']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictTradeType" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="空重">
                        <el-select v-model="condition['search_EQ_ef']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictIfHeavyType" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="船代">
                        <auto-search-custom @selectName="v=>condition['search_LIKE_shipAgentName']=v"
                                            :isShipAgent="true"></auto-search-custom>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="中转">
                        <el-select v-model="condition['search_EQ_change']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictOneOrZero" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="16" v-if="isSave">
                    <el-button type="primary" class="ml-80" @click="loadData">查 询</el-button>
                    <el-button @click="handleFormOpen(false)">添 加</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                    <excel-import code="XCJHQD" @getUploadData="handleImport"></excel-import>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="list" border stripe max-height="500" class="mt-10">
            <el-table-column type="index" fixed="left" align="center" label="序号" width="55"></el-table-column>
            <el-table-column prop="containerId" label="箱号"  min-width="120"></el-table-column>
            <el-table-column prop="containerType" label="箱型"  min-width="80"></el-table-column>
            <el-table-column prop="containerSize" label="尺寸"  min-width="80"></el-table-column>
            <el-table-column prop="sealNo" label="铅封号"  min-width="100"></el-table-column>
            <el-table-column prop="ef" label="空重"  min-width="80">
                <template slot-scope="scope">
                    {{ scope.row.ef | _filterIfHeavyType }}
                </template>
            </el-table-column>
            <el-table-column prop="tradeType" label="内外贸"  min-width="100">
                <template slot-scope="scope">
                    {{ scope.row.tradeType | _filterTradeType }}
                </template>
            </el-table-column>
            <el-table-column prop="enchaseWay" label="装箱方式"  min-width="110">
                <template slot-scope="scope">
                    {{ scope.row.enchaseWay | _filterEnchaseWayType }}
                </template>
            </el-table-column>
            <el-table-column prop="billNumber" label="提单号"  min-width="140"></el-table-column>
            <el-table-column prop="shipAgentName" label="船代"  min-width="140"></el-table-column>
            <el-table-column prop="change" label="中转"  min-width="80">
                <template slot-scope="scope">
                    {{ scope.row.change | _filterIsChange }}
                </template>
            </el-table-column>
            <el-table-column prop="cargoName" label="货名"  min-width="80"></el-table-column>
            <el-table-column prop="cargoCount" label="件数"  min-width="80"></el-table-column>
            <el-table-column prop="cargoWeight" label="货重"  min-width="80"></el-table-column>
            <el-table-column prop="containerWeight" label="箱货重"  min-width="100"></el-table-column>
            <el-table-column prop="cargoType" label="货类"  min-width="80"></el-table-column>
            <el-table-column prop="containerOwnerName" label="箱主"  min-width="110"></el-table-column>
            <el-table-column prop="loadPort" label="装货港"  min-width="100"></el-table-column>
            <el-table-column prop="unloadPort" label="卸货港"  min-width="100"></el-table-column>
            <!--<el-table-column prop="unloadArea" label="卸区"  min-width="100"></el-table-column>-->
            <el-table-column fixed="right" align="center" label="操作"  width="140">
                <template slot-scope="scope">
                    <el-button size="small" :disabled="form.planStatus==='FIVE'||form.planStatus==='SIX'" type="text"
                               @click="handleFormOpen(true,scope.row)">编辑
                    </el-button>
                    <el-button type="text" :disabled="form.planStatus==='FIVE'||form.planStatus==='SIX'" class="danger"
                               size="small" @click="handleRemove(scope.row.tallyDetailId)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row class="mt-10" type="flex" justify="space-between">
            <el-table :data="tradeType" show-summary :summary-method="getSummary" border stripe max-height="500">
                <el-table-column prop="tradeType" label="内外贸"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.tradeType | _filterTradeType }}
                    </template>
                </el-table-column>
                <el-table-column prop="ef" label="空重"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.ef | _filterIfHeavyType }}
                    </template>
                </el-table-column>
                <el-table-column prop="containerSize" label="尺寸"  min-width="80"></el-table-column>
                <el-table-column prop="cargoCount" label="箱数"  min-width="80"></el-table-column>
            </el-table>
            <el-table class="ml-20" :data="transfer" show-summary :summary-method="getSummary" border stripe
                      max-height="500">
                <el-table-column prop="change" label="中转"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.change | _filterIsChange }}
                    </template>
                </el-table-column>
                <el-table-column prop="tradeType" label="内外贸"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.tradeType | _filterTradeType }}
                    </template>
                </el-table-column>
                <el-table-column prop="ef" label="空重"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.ef | _filterIfHeavyType }}
                    </template>
                </el-table-column>
                <el-table-column prop="containerSize" label="尺寸"  min-width="80"></el-table-column>
                <el-table-column prop="cargoCount" label="箱数"  min-width="80"></el-table-column>
            </el-table>
        </el-row>
        <el-row class="mt-10">
            <el-table :data="shipAgent" show-summary :summary-method="getSummary" border stripe max-height="500">
                <el-table-column prop="shipAgentName" label="船代"  min-width="80"></el-table-column>
                <el-table-column prop="tradeType" label="内外贸"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.tradeType | _filterTradeType }}
                    </template>
                </el-table-column>
                <el-table-column prop="ef" label="空重"  min-width="80">
                    <template slot-scope="scope">
                        {{ scope.row.ef | _filterIfHeavyType }}
                    </template>
                </el-table-column>
                <el-table-column prop="containerSize" label="尺寸"  min-width="80"></el-table-column>
                <el-table-column prop="cargoCount" label="箱数"  min-width="80"></el-table-column>
            </el-table>
        </el-row>
        <ship-load-form v-if="dialogForm" :id="id" ref="shipLoadForm" @load="loadData"></ship-load-form>
    </div>
</template>

<script>
    import {
        getShipPlanId,
        getShipPlanIdList,
        editShipPlan,
        addShipPlan,
        getShipPlanList,
        deleteShipPlanList,
        shipPlanTradeType,
        shipPlanTransfer,
        shipPlanShipAgent,
        shipPlanInport,
        createFromExcel
    } from "@/api/shipPlan/shipPlan";
    import autoSearchShip from '@/components/autocomplete/autoSearchShip'
    import autoSearchSize from '@/components/autocomplete/autoSearchSize'
    import autoSearchEntrust from "@/components/autocomplete/autoSearchEntrust";
    import autoSearchCustom from '@/components/autocomplete/autoSearchCustom'
    import shipLoadForm from './shipLoadForm'
    import selectPort from '@/components/select/selectPort'
    import { newExportExcel } from "@/utils/newExport";
    import { ifHeavyType, tradeType, enchaseWayType, isChange } from "../../../assets/dict";
    import excelImport from '@/components/excel/import'
    import attachments from '@/components/file-upload'
    import { getSystemParameterList } from "@/api/system/systemParameter";

    export default {
        name: "创建卸船计划",
        components: {
            autoSearchShip, autoSearchSize, autoSearchEntrust, autoSearchCustom, shipLoadForm, selectPort, excelImport, attachments
        },
        data() {
            return {
                id: '',
                form: {},
                rules: {},
                condition: {},
                list: [],
                shipAgent: [],
                tradeType: [],
                transfer: [],
                dialogForm: false,
                reload: true,
                isSave: false,
                created: true,
                totalNum: 0,
                twoSize: 0,
                fourSize: 0,
                change: 0,
                noChange: 0,
                inNum: 0,
                outNum: 0,
                cang: 0,
                gang: 0,
                titleMessage:[],
                isSingle: true,
                isLimit: 1,
                btnName : "上传卸船计划"
            }
        },
        mounted() {
            this.getData()
        },
        activated() {
            if (!this.created) {
                this.getData()
            }
        },
        methods: {
            loadData() {
                getShipPlanId(this.id).then(res => {
                    this.form = res.data
                    const condition = this.$assist.copySearchConditions(this.condition)
                    getShipPlanIdList(this.id, condition).then(response => {
                        this.created = false
                        this.list = response.data.aaData
                        this.totalNum = this.list.length
                        this.twoSize = 0
                        this.fourSize = 0
                        this.change = 0
                        this.noChange = 0
                        this.inNum = 0
                        this.outNum = 0
                        this.cang = 0
                        this.gang = 0
                        this.list.forEach(f => {
                            if (f.containerSize == 20) {
                                this.twoSize = this.twoSize + 1
                            }
                            if (f.containerSize == 40) {
                                this.fourSize = this.fourSize + 1
                            }
                            if (f.change === '1') {
                                this.change = this.change + 1
                            }
                            if (f.change === '0') {
                                this.noChange = this.noChange + 1
                            }
                            if (f.tradeType === 'I') {
                                this.inNum = this.inNum + 1
                            }
                            if (f.tradeType === 'O') {
                                this.outNum = this.outNum + 1
                            }
                            if (f.enchaseWay === 'GZ') {
                                this.gang = this.gang + 1
                            }
                            if (f.enchaseWay === 'CZ') {
                                this.cang = this.cang + 1
                            }
                        })
                    })
                    shipPlanTradeType(this.id, condition).then(response => {
                        this.tradeType = response.data
                    })
                    shipPlanTransfer(this.id, condition).then(response => {
                        this.transfer = response.data
                    })
                    shipPlanShipAgent(this.id, condition).then(response => {
                        this.shipAgent = response.data
                    })
                }).catch(err => {
                    const view = { path: `/work/shipPlan/unloadAdd`, name: '创建卸船计划' }
                    this.$store.dispatch('delVisitedViews', view).then((views) => {
                        if (view.path === this.$route.path) {
                            this.$router.push({ path: '/work/shipPlan/unload', name: '卸船计划列表' })
                        } else {
                            this.$message({ message: '服务器错误!', type: 'error' })
                        }
                    })
                })
            },
            downExcel(){
                getSystemParameterList({ 'search_LIKE_paramCode': 'BACK_SERVICE_URL' }).then(res => {
                    if (res.data.aaData.length > 0) {
                        window.open(res.data.aaData[0].paramValue + "/excel/卸船计划模板_新.xls");
                    }
                })
            },
            uploadsExcel(val) {
                if (this.form.portCode == null || this.form.portCode == ""){
                    this.$message({ message: '请选择港口', type: 'warning' })
                    return
                }
                if (val == null || val == "" ){
                    this.$message({ message: '上传失败', type: 'warning' })
                    return
                }
                let fileId = val[0].id
                let planType = "XC"
                let portCode = this.form.portCode
                createFromExcel(planType, portCode, fileId).then(res => {
                    sessionStorage.setItem('unloadId', res.data)
                    this.$router.push({ path: '/work/shipPlan/unloadEdit', name: '编辑卸船计划' })
                })
            },
            handleSubmit() {
                if (this.isSave) {
                    let data = this.$assist.copySearchConditions(this.form)
                    editShipPlan(this.id, data).then(res => {
                        this.$message({ message: '编辑卸船计划成功!', type: 'success' })
                        this.loadData()
                    })
                } else {
                    let data = {
                        ...this.form,
                        planType: 'XC',
                        planStatus: 'ONE',
                        planFrom: 'EXCEL'
                    }
                    addShipPlan(data).then(res => {
                        this.$message({ message: '新增成功', type: 'success' })
                        this.isSave = true
                        this.id = res.data.shipPlanNo
                        this.loadData()
                    })
                }
            },
            handleFormOpen(bool, item) {
                this.dialogForm = true
                this.$nextTick(() => {
                    if (bool) {
                        this.$refs.shipLoadForm.form = JSON.parse(JSON.stringify(item))
                        this.$refs.shipLoadForm.isEdit = true
                    }
                    this.$refs.shipLoadForm.dialogForm = true
                })
            },
            handleRemove(id) {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteShipPlanList(id).then(res => {
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.loadData()
                    })
                })
            },
            getSummary(params) {
                const { columns, data } = params
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value)) && column.property === 'cargoCount') {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += ' ';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            getData() {

                //
                //
                // const view = { path: `/work/shipPlan/unloadEdit`, name: '编辑卸船计划' }
                // this.id = sessionStorage.getItem('unloadId')
                // if (this.id) {
                //     this.loadData()
                // } else {
                //     this.$store.dispatch('delVisitedViews', view).then((views) => {
                //         if (view.path === this.$route.path) {
                //             const latestView = views.slice(-1)[0]
                //             if (latestView) {
                //                 this.$router.push(latestView.path)
                //             } else {
                //                 this.$router.push({ path: '/work/shipPlan/unload', name: '卸船计划' })
                //             }
                //         }else{
                //             this.$message({ message: '服务器错误!', type: 'error' })
                //         }
                //     })
                // }
            },
            handleImport(val) {
                console.log(val)
                shipPlanInport(this.id, val).then(res => {
                    this.$message({ message: '导入成功!', type: 'success' })
                    this.loadData()
                })
            },
            handleExport() {
                let map = new Map();
                map.set("containerId", "箱号")
                map.set("containerType", "箱型")
                map.set("containerSize", "尺寸")
                map.set("sealNo", "铅封号")
                map.set("ef", "空重")
                map.set("tradeType", "内外贸")
                map.set("enchaseWay", "装箱方式")
                map.set("billNumber", "提单号")
                map.set("shipAgentName", "船代")
                map.set("change", "中转")
                map.set("cargoName", "货名")
                map.set("cargoCount", "件数")
                map.set("cargoWeight", "货重")
                map.set("containerWeight", "箱货重")
                map.set("cargoType", "货类")
                map.set("containerOwnerName", "箱主")
                map.set("loadPort", "装货港")
                map.set("unloadPort", "卸货港")
                map.set("unloadArea", "卸区")
                let params = this.$assist.copySearchConditions(this.condition)
                params.search_EQ_planType = 'XC'
                getShipPlanIdList(this.id).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            if (key === "ef") {
                                record[key] = ifHeavyType.get(record[key]);
                            }
                            if (key === "tradeType") {
                                record[key] = tradeType.get(record[key]);
                            }
                            if (key === "enchaseWay") {
                                record[key] = isChange.get(record[key]);
                            }
                            if (key === "change") {
                                record[key] = enchaseWayType.get(record[key]);
                            }
                            exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("卸船计划明细", exportRecords);
                })
            }
        },
        watch: {
            $route(to, form) {
                if (form.name === '卸船计划列表') {
                    this.reload = false
                    this.$nextTick(() => {
                        this.reload = true
                    })
                }
            }
        }
    }
</script>

<style scoped>

</style>
